package com.tnovoselec.server.travelassistant.worker;

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.tnovoselec.server.travelassistant.Config;
import com.tnovoselec.server.travelassistant.util.XMLUtil;

public class ExchangeRatesParser implements IParser {

	private Document document = null;

	@Override
	public void parse() {
		parseExchangeRate();

	}

	@Override
	public Document getDoc() {
		return document;
	}

	@Override
	public String getXMLName() {
		return Config.EXCHANGE_RATES_XML_NAME;
	}

	private void parseExchangeRate() {
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpGet httpget = new HttpGet(Config.exchangeRateURL);
			ResponseHandler<String> responseHandler = new BasicResponseHandler();
			String responseBody = httpclient.execute(httpget, responseHandler);
			byte[] data = responseBody.getBytes();
			String temp = new String(data, "UTF-8");
			document = XMLUtil.getDoc(temp.getBytes());
			NodeList nodes = document.getDocumentElement().getElementsByTagName("Currency");
			for (int i = 0; i < nodes.getLength(); i++) {
				Element node = (Element) nodes.item(i);
				String name = XMLUtil.getChildNodeValue(node, "Name");
				XMLUtil.createElement(document, "image", Config.dropBoxPublicUrl + name + ".png", node);
			}
			document.normalize();

		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}
